package com.ayuan.blog.controller;

import com.ayuan.blog.bean.CommonResponseBean;
import com.ayuan.blog.domain.Image;
import com.ayuan.blog.service.ImageService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by xiaozhu on 16/8/14.
 */
@Log4j2
@Controller
@RequestMapping("image")
public class ImageController extends BaseController{

    @Autowired
    private ImageService imageService;

    @RequestMapping("add")
    @ResponseBody
    public Object add(HttpServletRequest request, Image image) {
        String validateMessage = validateImage(image);
        if (null != validateMessage) {
            return new CommonResponseBean<Object>(1, validateMessage, null);
        }

        try {
            image.setAccountId(Long.valueOf(getCurrentUser(request).getAccountId()));

            imageService.save(image);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new CommonResponseBean<Object>(1, "增加图片失败", null);
        }

        return new CommonResponseBean<Object>(0, "增加图片成功", null);
    }

    private String validateImage(Image image) {
        if (null == image) {
            return "参数不能为空";
        } else if (StringUtils.isNotEmpty(image.getUrl())) {
            return "url不能为空";
        }

        return null;
    }
}
